package Test;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

import Interact.Image;
import Interact.Interactable;
import Interact.Interface;
import Tool.Binaryable;
import Tool.Tool;

public class Illustration implements Binaryable{
	/**
	 *  插图
	 *  键是说明，值是图片 
	 */
	private AbstractMap<String, Image> imgs = new TreeMap<String, Image>();
	
	/**
	 * 添加插图
	 * @param key	插图说明
	 * @param img	插图
	 */
	public void putImage(String key, Image img){
		imgs.put(key, img);
	}
	
	/**
	 * 获取插图
	 * @param key	插图说明
	 */
	public Image getImage(String key){
		return imgs.get(key);
	}
	
	public Set<String> getInfos(){
		return imgs.keySet();
	}
	
	protected AbstractMap<String, Image> getValue(){
		return imgs;
	}

	@Override
	public void toBytes(OutputStream out) throws IOException {
		// 有几张图
		Tool.writeInt(imgs.size(), out);
		
		// 就写几张进去
		Iterator<Entry<String, Image>> iter = imgs.entrySet().iterator();
		
		while (iter.hasNext()){
			Entry<String, Image> value = iter.next();
			Tool.writeString(value.getKey(), out);
			value.getValue().toBytes(out);
		}
	}

	@Override
	public void fromBytes(InputStream in) throws IOException {
		imgs.clear();
		// 图片数
		for (int i = Tool.readInt(in); i > 0; --i){	
			String key = Tool.readString(in);
			Image value = new Image(in);
			imgs.put(key, value);
		}
	}
	
	public void display(Interface inf) throws IOException{
		Iterator<Entry<String, Image>> iter = imgs.entrySet().iterator();
		while (iter.hasNext()){
			Entry<String, Image> value = iter.next();
			inf.print("<br/>" + value.getKey() + ":<br/>");
			inf.print(value.getValue());
		}
	}
}
